package com.chenju.easyshotjava.core;

import javax.swing.KeyStroke;
import java.awt.event.KeyEvent;
import java.util.HashMap;
import java.util.Map;

public class KeyStrokeUtils {

    private static final Map<String, Integer> MODIFIER_MAP = new HashMap<>();
    private static final Map<String, Integer> KEY_CODE_MAP = new HashMap<>();

    static {
        MODIFIER_MAP.put("Ctrl", KeyEvent.CTRL_DOWN_MASK);
        MODIFIER_MAP.put("Shift", KeyEvent.SHIFT_DOWN_MASK);
        MODIFIER_MAP.put("Alt", KeyEvent.ALT_DOWN_MASK);
        MODIFIER_MAP.put("Meta", KeyEvent.META_DOWN_MASK);

        KEY_CODE_MAP.put("F1", KeyEvent.VK_F1);
        KEY_CODE_MAP.put("F2", KeyEvent.VK_F2);
        KEY_CODE_MAP.put("F3", KeyEvent.VK_F3);
        KEY_CODE_MAP.put("F4", KeyEvent.VK_F4);
        KEY_CODE_MAP.put("F5", KeyEvent.VK_F5);
        KEY_CODE_MAP.put("F6", KeyEvent.VK_F6);
        KEY_CODE_MAP.put("F7", KeyEvent.VK_F7);
        KEY_CODE_MAP.put("F8", KeyEvent.VK_F8);
        KEY_CODE_MAP.put("F9", KeyEvent.VK_F9);
        KEY_CODE_MAP.put("F10", KeyEvent.VK_F10);
        KEY_CODE_MAP.put("F11", KeyEvent.VK_F11);
        KEY_CODE_MAP.put("F12", KeyEvent.VK_F12);
        // 可以添加更多功能键
    }

    public static KeyStroke stringToKeyStroke(String input) {
        if ("".equals(input) || input == null) {
            return KeyStroke.getKeyStroke("F5");
        }
        String[] parts = input.split("\\+");
        int modifiers = 0;
        int keyCode = 0;

        for (int i = 0; i < parts.length; i++) {
            String part = parts[i].trim();
            if (i == parts.length - 1) {
                Integer code = KEY_CODE_MAP.get(part);
                if (code != null) {
                    keyCode = code;
                } else {
                    keyCode = KeyEvent.getExtendedKeyCodeForChar(part.charAt(0));
                }
            } else {
                Integer modifier = MODIFIER_MAP.get(part);
                if (modifier != null) {
                    modifiers |= modifier;
                }
            }
        }

        return KeyStroke.getKeyStroke(keyCode, modifiers);
    }

    public static String keyStrokeToString(KeyStroke keyStroke) {
        StringBuilder sb = new StringBuilder();
        if (keyStroke == null) {
            return sb.toString();
        }
        int modifiers = keyStroke.getModifiers();
        if ((modifiers & KeyEvent.CTRL_DOWN_MASK) != 0) {
            sb.append("Ctrl+");
        }
        if ((modifiers & KeyEvent.SHIFT_DOWN_MASK) != 0) {
            sb.append("Shift+");
        }
        if ((modifiers & KeyEvent.ALT_DOWN_MASK) != 0) {
            sb.append("Alt+");
        }
        if ((modifiers & KeyEvent.META_DOWN_MASK) != 0) {
            sb.append("Meta+");
        }
        sb.append(KeyEvent.getKeyText(keyStroke.getKeyCode()));
        return sb.toString();
    }
}